package UILayer;
import java.util.Scanner;
import ControlLayer.*;
import ModelLayer.*;

/**
 * Write a description of class OrderUI here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class OrderUI
{
    // instance variables - replace the example below with your own
    private OrderController orderController;
    private Scanner reader;
    private PersonController personController;
    /**
     * Constructor for objects of class OrderUI
     */
    public OrderUI()
    {
        personController = new PersonController();
        orderController = new OrderController();
        reader = new Scanner(System.in);
        orderMenu();
    }
    
    public void orderMenu()
    {   
        boolean exit = false;
        while(!exit)
        {
            int choise = writeOrderMenu();
            if (choise == 1)
            {
                createOrder();
            }
            else
            {
                if(choise == 2)
                {
                    findOrderById();
                }
                else
                {
                    if(choise == 3)
                    {
                        findOrderByName();
                    }
                    else
                    {
                        if(choise == 4)
                        {
                            listAllOrders();
                        }
                        else
                        {
                            if(choise == 5)
                            {
                                deleteOrder();
                            }
                            else
                            {
                                exit = true;
                            }
                        }
                    }
                }
            }
        }
    
    }

    private int writeOrderMenu()
    {
           // creates an object keyboard to read data from the keyboard
            
            System.out.println("\f *** Order Menu ***");
            System.out.println("(1) Create order");
            System.out.println("(2) Find order by id (See Registred customers phonenumber)");
            System.out.println("(3) Find order by customers name");
            System.out.println("(4) List all orders");
            System.out.println("(5) Delete order");
            System.out.println("");
            System.out.println("(0) Return to MainMenu");
            System.out.print("\n Make your choise: ");
            
            int choise = UIInput.inputInt();
            return choise;
    }

    private void createOrder()
    {
        System.out.println("\f- Create order -");
        System.out.print("Enter customers name: ");
        String customersName = reader.nextLine();
        
        String timeAndDate = orderController.timeAndDate();
        orderController.createOrder(customersName);
        
        int ordreId = orderController.getLastCreatedOrderId();
        System.out.println("Order ID: " + ordreId  + " Date: " + timeAndDate + " are now created");
        
        createOrderMenu1Or0();
    }
    
    private void createPartOrders()
    {
        System.out.print("Enter barcode: ");
        String barcode = reader.nextLine();
        if(orderController.findItemByBarcode(barcode) != null)
        {
            System.out.println("Barcode:         " + orderController.findItemByBarcode(barcode).getBarcode());
            System.out.println("Item nb:         " + orderController.findItemByBarcode(barcode).getItemNumber());
            System.out.println("Name:            " + orderController.findItemByBarcode(barcode).getName());
            System.out.println("Price:           " + orderController.findItemByBarcode(barcode).getSellingPrice());
            System.out.println("Amount in stock: " + orderController.findItemByBarcode(barcode).getAmountInStock());
            System.out.println("");
            System.out.print("Amount you want to sell: ");
            int amount = UIInput.inputInt();
            
            if(amount > orderController.findItemByBarcode(barcode).getAmountInStock())
            {
                System.out.println("The amount is not available");
            }
            else
            {
                orderController.createPartOrderAndAddToOrder(amount, barcode);
                System.out.println("Partorder added to order");
            }
        }
        else
        {
            System.out.println("Barcode not found or Order id is not valid");
            System.out.println("");
        }
        
    }
    
    private void createOrderMenu1Or0()
    {
        boolean stop = false;
        while(!stop) {
            System.out.println("");
            System.out.print("Press 1 to enter item | press 0 to go to invoice: ");
            int i = UIInput.inputInt();
            if(i == 1) 
            {
                createPartOrders();
            }
            
            else 
            {
                stop = true;
                orderController.calculateOrderPrice();
                confirmOrder();
                sentToStockWorkers();
            }
        }
        back();
    }
    
    private void confirmOrder()
    {
        int index = 0;
        int orderIndex = orderController.getLastCreatedOrderId()-1;
        
        System.out.println("\f- Order " + orderController.getLastCreatedOrderId() + " -");
        printPartOrdersToFindOrder(index, orderIndex);
        System.out.println("");
        System.out.println("Total without VAT:               VAT:              Total with VAT:");
        System.out.println(orderController.listAllOrder().get(orderIndex).getWithoutVAT() + "                           " + orderController.listAllOrder().get(orderIndex).getVATPrice() + "             " + orderController.listAllOrder().get(orderIndex).getTotalPrice());
    }
    
    private void sentToStockWorkers()
    {
        System.out.print("Confirm order. Press 1 to sent to stockworker. | Press 2 to abort: ");
        int pay = UIInput.inputInt();
        int orderIndex = orderController.getLastCreatedOrderId()-1;
        if(pay == 1)
        {
            if(orderController.listAllOrder().get(orderIndex).getPartOrders().size() < 1)
            {
                System.out.println("You have no items. You have to abort");
                orderController.listAllOrder().get(orderIndex).setStatus("canceled");
            }
            else
            {
                System.out.println("Sent to stockworker");
                orderController.listAllOrder().get(orderIndex).setStatus("stock");
            }
        }
        else
        {
            try
            {
                orderController.deleteOrder(orderIndex+1);
                System.out.println("Order canceled");
            }
            catch (Exception e)
            {
                System.out.println(e.getMessage());
            }
        }
    }
    
    private void findOrderById()
    {
        System.out.println("\f- Find order -");      
        System.out.print("Please enter the id of the Order you want to find: ");
        int id = UIInput.inputInt();
        try
        {
              if(orderController.findOrder(id) != null)
              {
                  int index = 0;
                  int orderIndex = id-1;
                  System.out.println("\f- ORDER " + id + " -");
                  System.out.println("Items:");
                  System.out.println("Customer name: " + orderController.findOrder(id).getCustomersName());
                  System.out.println("----------------------");
                  
                  printPartOrdersToFindOrder(index, orderIndex);
                  
                  System.out.println("");
                  System.out.println("Total without VAT:              Total with VAT:");
                  System.out.println(orderController.listAllOrder().get(orderIndex).getWithoutVAT() + "                           " + orderController.listAllOrder().get(orderIndex).getTotalPrice());
                  System.out.println("Status on order: " + orderController.listAllOrder().get(id-1).getStatus()); 
                  System.out.println("--------------------------------------------------------");
              
                  if(orderController.findOrder(id).getOrderedBy() != null)
                  {
                   Person newPerson = orderController.getBuyerInfo(id);
                   String personType = personController.checkObjectType(newPerson);
                   
                   if(personType.equals("PrivateCustomer"))
                   {
                        System.out.println("Customers phone number: " + ((RegisteredCustomer)newPerson).getPhoneNumber()); 
                   }
                   if(personType.equals("BusinessCustomer"))
                   {
                        System.out.println("Customers phone number: " + ((RegisteredCustomer)newPerson).getPhoneNumber());
                   }
                   if(personType.equals("WarehouseEmployee"))
                   {
                       System.out.println("WarehouseEmployee phone number: " + ((Employee)newPerson).getPhoneNumber());
                    }
                   if(personType.equals("Manager"))
                   {
                       System.out.println("Managers phone number: " + ((Employee)newPerson).getPhoneNumber());
                   }
                   if(personType.equals("Salesman"))
                   {
                       System.out.println("Salesmans phone number: " + ((Employee)newPerson).getPhoneNumber());
                   }
                }
            }
        }
        
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        back();
    }
    
    private void findOrderByName()
    {
        System.out.println("\f- Find order by name -");      
        System.out.print("Please enter the customers name: ");
        String customersName = reader.nextLine();
        try
        {
            int index0 = 0;
            while(index0 < orderController.findOrderByName(customersName).size())
            {
                int id = orderController.findOrderByName(customersName).get(index0).getId();
                int index = 0;
                int orderIndex = id-1;
                System.out.println("- ORDER " + id + " -");
                System.out.println("Customers name: " + orderController.findOrder(id).getCustomersName());
                System.out.println("Items:");
                System.out.println("----------------------");
                
                printPartOrdersToFindOrder(index, orderIndex);
                
                System.out.println("");
                System.out.println("Total without VAT:              Total with VAT:");
                System.out.println(orderController.listAllOrder().get(orderIndex).getWithoutVAT() + "                           " + orderController.listAllOrder().get(orderIndex).getTotalPrice());
                System.out.println("Status on order: " + orderController.listAllOrder().get(id-1).getStatus());
                System.out.println("--------------------------------------------------------");
                index0++;
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        back();
    }
    
    private void printPartOrdersToFindOrder(int index, int orderIndex)
    {
        while(index < orderController.listAllOrder().get(orderIndex).getPartOrders().size())
        {
            double price = orderController.listAllOrder().get(orderIndex).getPartOrders().get(index).getItem().getSellingPrice();
            int amount = orderController.listAllOrder().get(orderIndex).getPartOrders().get(index).getAmount();
            double totalPrice = price * amount;
            double totalpriceNoVAT = totalPrice - (totalPrice * orderController.listAllOrder().get(orderIndex).getVAT());
            System.out.println("Barcode: " + orderController.listAllOrder().get(orderIndex).getPartOrders().get(index).getItem().getBarcode());
            System.out.println("Name: " + orderController.listAllOrder().get(orderIndex).getPartOrders().get(index).getItem().getName());
            System.out.println("Price: " + price);
            System.out.println("Amount: " + amount);
            System.out.println("");
                        
            System.out.println("Price with No VAT: " + totalpriceNoVAT);
            System.out.println("Price with VAT   : " + totalPrice);
            System.out.println("----------------------");
            index++;
        }
    }
    
    private void deleteOrder()
    {
        System.out.println("\f- Delete order -");
        System.out.println("Please enter the id of the Order you want to delete:");
        int id = UIInput.inputInt();
        try
        {
            orderController.deleteOrder(id);
            System.out.println("Order is deleted");
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        back();
    }
    
    private void listAllOrders()
    {
        int index = 0;
        System.out.println("\f- List of all orders -");
        
       System.out.println("| ID |   | Date |    |Customer name|   | Nb of items |  | Status |  | Total |"); 
       while(index < orderController.listAllOrder().size()) 
       {
          int Id = orderController.listAllOrder().get(index).getId(); 
          String date = orderController.listAllOrder().get(index).getDate();
          String customerName = orderController.listAllOrder().get(index).getCustomersName();
          int items = orderController.listAllOrder().get(index).getPartOrders().size();
          String status = orderController.listAllOrder().get(index).getStatus();
          double total = orderController.listAllOrder().get(index).getTotalPrice();
          
          System.out.println("  " + Id + "      " + date + "      " + customerName + "                 " + items + "           " + status + "        " + total);
          
          index++;
          System.out.println("");
        }  
       back();
    }
    
    private void back()
    {
        System.out.println("");
        System.out.print("Press 'enter' to get back to menu");
        String i = reader.nextLine();
    }
}
